//
//  User.m
//  itaka
//
//  Created by Robert Soszynski on 1/18/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "User.h"

@implementation User 
@synthesize delegate, username, password, domain;

- (NSString*) login {
    if (username) {
        return [NSString stringWithFormat:@"%@%@", username, domain];
    } else
        return @"";
}

- (void) signIn: (NSString*) u: (NSString*) p: (NSString*) d {
    [self setUsername:[[u stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lowercaseString]];
    [self setPassword:p];
    [self setDomain:d];
    
    [self authentication:[self login] :[self password]];
}

- (void) signOut {
    [self setUsername:nil];
    [self setPassword:nil];
    [self setDomain:nil];
}

- (void) authentication:(NSString *)login :(NSString *)password {
    //https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email=...&Passwd=...
    
    NSString *requestString = [NSString stringWithFormat:@"accountType=%@&Email=%@&Passwd=%@", @"HOSTED_OR_GOOGLE", [self login], [self password]];
    NSData *requestData = [ NSData dataWithBytes: [ requestString UTF8String ] length: [ requestString length ] ];
    NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: @"https://www.google.com/accounts/ClientLogin" ] ]; 
    
    [ request setHTTPMethod: @"POST" ];
    [ request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [ request setHTTPBody: requestData ];
    
    NSURLResponse *response;
    NSError *error;
    
    NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];
    NSString* content = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    if (error == nil) {
        NSMutableDictionary *pairs = [NSMutableDictionary dictionary];
        
        
        for (NSString *pairString in [content componentsSeparatedByString:@"&"]) {
            NSArray *pair = [pairString componentsSeparatedByString:@"="];
            if ([pair count] < 2)
                continue;
            
            [pairs setObject:[pair objectAtIndex:1] forKey:[pair objectAtIndex:0]];
        }
        
        if ([pairs objectForKey:@"SID"])
            [[self delegate] authenticated];
        else
            [[self delegate] authenticationError:[pairs objectForKey:@"Error"]];
    } else {
        NSString *err;
        if ((err = [[error userInfo] objectForKey:@"NSLocalizedDescription"])) {}
        else if ((err = [[error userInfo] objectForKey:@"error"])) {}
    
        [[self delegate] authenticationError: err];
    }
}

@end
